# -*- coding: utf-8 -*-
#
# encode-xvid - Encode de vídeos em formato mpeg4 (xvid)/mp3
# URLs: http://code.google.com/p/encode-xvid/, http://estacaozn.blogspot.com
# Copyright 2011 Felipe Guerço Oliveira - felipeguerco@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Classe responsável por executar o script e exibir seu retorno

import gtk
import glib
import shlex
import time
import subprocess
from LogWindow import LogWindow

class ScriptRunner(object):
	log = None

	def run(self, script, video, legenda, video_bitrate, audio_bitrate, volume, output, simulacao):
		cmd = script
		if video:
			cmd += " -v " + video
		if legenda:
			cmd += " -l " + legenda
		if video_bitrate:
			cmd += " -vb " + video_bitrate
		if audio_bitrate:
			cmd += " -ab " + audio_bitrate
		if volume:
			cmd += " -vol " + volume
		if output:
			cmd += " -o " + output
		if simulacao:
			cmd += " -sim "

		self.log = LogWindow()
		self.log.show_dialog()

		proc = subprocess.Popen(shlex.split(cmd), stdout = subprocess.PIPE, stderr = subprocess.PIPE)
		
		glib.io_add_watch(proc.stdout,      # file descriptor
				glib.IO_IN,                 # condition
				self.write_to_buffer)       # callback

		glib.io_add_watch(proc.stderr,      # file descriptor
				glib.IO_IN,                 # condition
				self.write_to_buffer)       # callback

	def write_to_buffer(self, fd, condition):
		if condition == glib.IO_IN:
			self.log.add_line(fd.readline())
 			return True
		else:
 			return False
	
